package com.shuo.dsa.leetcode;

import java.util.*;

/**
 * Created by shuoGG on 2018/10/6 0006
 */
public class WordBreak2 {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("cat");
        set.add("cats");
        set.add("and");
        set.add("sand");
        set.add("dog");
        System.out.println(new WordBreak2().wordBreak("catsanddog", set));
    }

    public ArrayList<String> wordBreak(String s, Set<String> dict) {
        return DFS(s, dict, new HashMap<>());
    }

    private ArrayList<String> DFS(String s, Set<String> dict, Map<String, ArrayList<String>> map) {
        if (map.containsKey(s))
            return map.get(s);
        ArrayList<String> res = new ArrayList<>();
        if (s.length() == 0) {
            res.add("");
            return res;
        }
        for (String word : dict) {
            if (s.startsWith(word)) {
                for (String str : DFS(s.substring(word.length()), dict, map)) {
                    res.add(word + (str.equals("") ? "" : " ") + str);
                }
            }
        }
        map.put(s, res);
        return res;
    }
}
